# -*- coding: utf-8 -*-

import time
from report import report_sxw
import pooler
from osv import osv
from tools.translate import _
import random
from datetime import datetime
        
class Parser(report_sxw.rml_parse):
        
    def __init__(self, cr, uid, name, context):
        super(Parser, self).__init__(cr, uid, name, context=context)
        self.context = context
        self.localcontext.update({
            'init': self._init,
            'all_weeks': self._get_all_weeks,
            'all_sessions': self._get_all_sessions,
            'all_sessions_info': self._get_all_sessions_info,
            'all_week_states': self._get_all_week_states,
            'seq_sessions': self._get_seq_sessions,
        })
    
    def _init(self, plan):
        plan_id = plan.id
        
        self.all_week_states = []
        sql = '''
            SELECT code, name
            FROM aas_academic_week_state
        '''
        self.cr.execute(sql)
        if self.cr.rowcount > 0:
            self.all_week_states = [(code, name) for (code, name) in self.cr.fetchall()]
            
        self.all_weeks = []
        sql = '''
            SELECT number
            FROM aas_academic_week
            WHERE academic_year = %s
            ORDER BY number
        '''
        self.cr.execute(sql, (plan.academic_year.id,))
        if self.cr.rowcount > 0:
            self.all_weeks = [id for (id,) in self.cr.fetchall()]
            
        self.seq_sessions = []
        self.all_sessions_info = {}
        self.all_sessions = []
        sql = '''
            SELECT id, name
            FROM aas_academic_session
            ORDER BY seq
        '''
        self.cr.execute(sql)
        if self.cr.rowcount > 0:
            self.all_sessions = [[id, unicode(name)] for (id, name) in self.cr.fetchall()]
        
        for session_id, session_name in self.all_sessions:
            if not self.all_sessions_info.has_key(session_name):
                self.all_sessions_info[session_name] = {}
            sql = '''
                SELECT aapl.academic_week, aaws.code
                FROM aas_academic_plan_line aapl JOIN aas_academic_week_state aaws ON aapl.academic_week_state = aaws.id
                WHERE aapl.academic_plan = %s AND 
                    aapl.academic_session = %s
            '''
            self.cr.execute(sql, (plan_id, session_id))
            if self.cr.rowcount > 0:
                for week_id, code in self.cr.fetchall():
                    self.all_sessions_info[session_name].update({week_id: code})

        temp_list = []
        temp_dict = {}
        for session_id, session_name in self.all_sessions:
            if self.all_sessions_info.has_key(session_name):
                if self.all_sessions_info[session_name] in temp_list:
                     index = temp_list.index(self.all_sessions_info[session_name])
                     if temp_dict.has_key(index):
                         if session_name not in temp_dict[index]:
                             old_value = '\n'.join(temp_dict[index])
                             temp_dict[index].append(session_name)
                             ss_index = -1
                             if old_value in self.seq_sessions:
                                 ss_index = self.seq_sessions.index(old_value)
                             new_value = '\n'.join(temp_dict[index])
                             if ss_index < 0:
                                 self.seq_sessions.append(new_value)
                             else:
                                 self.seq_sessions[ss_index] = new_value
                     else:
                         temp_dict.update({index: [session_name]})
                else:
                    temp_list.append(self.all_sessions_info[session_name])
                    temp_dict.update({temp_list.index(self.all_sessions_info[session_name]): [session_name]})
                    self.seq_sessions.append('\n'.join(temp_dict[temp_list.index(self.all_sessions_info[session_name])]))
        
        temp_result = {}
        for index in temp_dict.keys():
            if temp_dict[index]:
                temp_result.update({'\n'.join(temp_dict[index]): self.all_sessions_info[temp_dict[index][0]]})
        
        temp = []
        for ss in self.seq_sessions:
            if temp_result.has_key(ss):
                temp.append(ss)
        self.seq_sessions = temp
        self.all_sessions_info = temp_result
        
        points = []
        year_obj = self.pool.get('aas.academic.year')
        year = year_obj.browse(self.cr, self.uid, plan.academic_year.id)
        for semester in year.academic_semesters:
            if semester.academic_weeks:
                points.append(semester.academic_weeks[0].number)
                continue 
        if points:
            for key in self.all_sessions_info.keys():
                value = self.all_sessions_info[key]
                point_index = 0 
                t = 0
                for week_number in value.keys():
                    if value[week_number] == '/':
                        if len(points) > point_index and week_number >= points[point_index]:
                            point_index += 1
                            t = 1
                        else:
                            t += 1
                        value[week_number] = t 
                self.all_sessions_info[key] = value
        return True
        
    def _get_all_weeks(self):
        return self.all_weeks
    
    def _get_all_sessions(self):
        return self.all_sessions   

    def _get_all_sessions_info(self):
        return self.all_sessions_info
    
    def _get_all_week_states(self):
        return [(code, name) for (code, name) in self.all_week_states if code != '/' ]
    
    def _get_seq_sessions(self):
        return self.seq_sessions
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
